package com.ruoyi.web.controller.tool.designpattern.behavioralPatterns.memento;

/**
 * 备忘录模式
 *
 * @author Hack2003
 * @date 2024/3/21 18:12
 **/
import java.util.ArrayList;
import java.util.List;

// 发起人角色
class Originator {
    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    // 创建一个备忘录对象并保存当前状态
    public Memento createMemento() {
        return new Memento(state);
    }

    // 使用备忘录对象恢复状态
    public void restoreMemento(Memento memento) {
        state = memento.getState();
    }
}

// 备忘录角色
class Memento {
    private String state;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }
}

// 管理者角色
class CareTaker {
    private List<Memento> mementos = new ArrayList<>();

    public void addMemento(Memento memento) {
        mementos.add(memento);
    }

    public Memento getMemento(int index) {
        return mementos.get(index);
    }
}

// 示例代码
public class Test {
    public static void main(String[] args) {
        Originator originator = new Originator();
        CareTaker careTaker = new CareTaker();

        // 设置发起人状态
        originator.setState("State 1");
        System.out.println("发起人状态: " + originator.getState());

        // 创建备忘录并保存发起人状态
        Memento memento = originator.createMemento();
        careTaker.addMemento(memento);

        // 改变发起人状态
        originator.setState("State 2");
        System.out.println("发起人状态: " + originator.getState());

        // 恢复发起人状态
        originator.restoreMemento(careTaker.getMemento(0));
        System.out.println("发起人状态: " + originator.getState());
    }
}
